package com.bom.core.util.result;

import cn.hutool.http.HttpStatus;
import lombok.Builder;
import lombok.Getter;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Consumer;

/**
 * <pre>
 *     {@link Result}: 结果集
 * </pre>
 *
 * @author 毛博
 * @date 2021-12-15
 * @time 14:37:37
 */
@Getter
@Builder
public class Result<M> {

    private final Integer code;//状态码
    private final String msg;//提示消息
    private final Boolean success;//期望数据
    private final M data;//数据本体
    private final Long total;//总条数
    private final Map<String, Object> extra;//拓展数据

    public static class ResultBuilder<M> {

        private void code(Integer code) {
            this.code = code;
        }

        private void msg(String msg) {
            this.msg = msg;
        }

        private void data(M data) {
            this.data = data;
        }

        private ResultBuilder<M> extra(Map<String, Object> extra) {
            this.extra = extra;
            return this;
        }

        private void total(Long total) {
            this.total = total;
        }

        public ResultBuilder<M> ext(Consumer<Map<String, Object>> ext) {
            this.extra(new LinkedHashMap<>());
            ext.accept(this.extra);
            return this;
        }

        public ResultBuilder<M> success(M data, String msg, Long total) {
            this.code(HttpStatus.HTTP_OK);
            this.msg(msg);
            this.data(data);
            this.success = true;
            this.total(total);
            return this;
        }

        public ResultBuilder<M> success(M data, String msg) {
            return this.success(data, msg, 0L);
        }

        public ResultBuilder<M> fail(String msg) {
            return this.fail(null, msg);
        }

        public ResultBuilder<M> fail(M data, String msg) {
            this.code(HttpStatus.HTTP_BAD_REQUEST);
            this.msg(msg);
            this.success = false;
            this.data = data;
            return this;
        }
    }
}
